//
//  ViewController.swift
//  MVP2
//
//  Created by 李煜 on 2024/6/21.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }


}

import Alamofire

// 定义 Model
struct User: Codable {
    let id: Int
    let name: String
}

// 定义 View 协议
protocol UserViewProtocol: AnyObject {
    //加载指示
    func showLoading()
    //隐藏指示
    func hideLoading()
    
    func showUsers(users: [User])
    //提示错误
    func showError(message: String)
}

// 定义 Presenter
class UserPresenter {
    private weak var view: UserViewProtocol?
    
    init(view: UserViewProtocol) {
        self.view = view
    }
    
    func fetchUsers() {
        view?.showLoading()
        AF.request("https://example.com/fetchuser").responseDecodable(of: [User].self) { response in
            self.view?.hideLoading()
            
            switch response.result {
            case let .success(users):
                self.view?.showUsers(users: users)
            case let .failure(error):
                self.view?.showError(message: error.localizedDescription)
            }
        }

    }
}

// 定义 View 实现
class UserViewController: UIViewController, UserViewProtocol {
    func showLoading() { debugPrint("加载中") }
    func hideLoading() { debugPrint("隐藏指示器") }
    
    // 展示用户列表的方法
    func showUsers(users: [User]) {
        // 在这里更新 UI 显示用户列表
        print(users)
    }
    
    // 展示错误的方法
    func showError(message: String) {
        // 在这里显示错误信息
        print(message)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let presenter = UserPresenter(view: self)
        presenter.fetchUsers()
    }
}
